using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ThirdPersonCamera : MonoBehaviour
{
    public Transform target;
    public float distance = 5f;
    public float height = 2f;
    public float rotationSpeed = 10f;
    public float smoothing = 6f;
    public float minAngle = -30f;
    public float maxAngle = 60f;

    private float currentX;
    private float currentY;
    private Vector3 desiredPosition;
    private RaycastHit hit;

    private void Start()
    {
        // Lock mouse cursor
        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;
    }

    private void LateUpdate()
    {
        if (target == null) return;

        // Get mouse input
        currentX += Input.GetAxis("Mouse X") * rotationSpeed;
        currentY -= Input.GetAxis("Mouse Y") * rotationSpeed;
        currentY = Mathf.Clamp(currentY, minAngle, maxAngle);

        // Calculate camera position
        Quaternion rotation = Quaternion.Euler(currentY, currentX, 0);
        Vector3 direction = new Vector3(0, 0, -distance);
        desiredPosition = target.position + rotation * direction + Vector3.up * height;

        // Prevent camera from going through walls
        if (Physics.Linecast(target.position + Vector3.up, desiredPosition, out hit))
        {
            // Slightly offset to avoid wall penetration
            desiredPosition = hit.point + hit.normal * 0.2f;
        }

        // Smooth camera movement
        transform.position = Vector3.Lerp(transform.position, desiredPosition, smoothing * Time.deltaTime);
        transform.LookAt(target.position + Vector3.up * 1.5f); // Look at chest level
    }
}
